package com.speechb.modules.shiro;

import com.speechb.modules.system.admin.service.ISysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 登录验证
 */
public class CustomShiroRealm extends AuthorizingRealm {
    private final static Logger logger = LoggerFactory.getLogger(CustomShiroRealm.class);
    @Autowired
    ISysUserService sysUserService;
    //角色权限和对应权限添加
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        String name = (String) principalCollection.getPrimaryPrincipal();
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        //添加角色
        simpleAuthorizationInfo.addRole("admin");

        //添加权限
        simpleAuthorizationInfo.addStringPermission("create");

        return simpleAuthorizationInfo;
    }

    //用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken atoken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) atoken;

        String name = token.getUsername();
        if(StringUtils.isEmpty(name)) {
            logger.debug("username is empty");
            return null;
        }
        String passowrd = sysUserService.findPassword(name);
        if(StringUtils.isEmpty(passowrd)) {
            logger.debug("password is empty");
            return null;
        }
        //这里验证authenticationToken和simpleAuthenticationInfo的信息
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, passowrd, getName());
        return simpleAuthenticationInfo;

    }
}